package com.yxd.server;

import com.yxd.bootstrap.Constants;
import com.yxd.util.StrKit;

import javax.servlet.ServletOutputStream;
import javax.servlet.ServletResponse;
import java.io.*;
import java.util.Locale;

/**
 * Created by Administrator on 2016/6/15.
 */
public class Response implements ServletResponse {

    private final OutputStream outputStream;
    private PrintWriter printWriter;
    private Request request;


    public Response(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    public void setRequest(Request request) {
        this.request = request;
    }

    public void sendStaticResource() {
        String str = request.getUri();
        if (StrKit.isWhiteSpaceOrNull(str) || str.equals("/")) {
            str = "index.html";
        }
        try {
            String path = Constants.WRB_ROOT + File.separator + str;
            File file = new File(path);
            if (file.exists()) {
                FileInputStream fileInputStream = new FileInputStream(file);
                byte[] bytes = new byte[2048];
                while (fileInputStream.read(bytes) != -1) {
                    outputStream.write(bytes);
                }
            } else {
                String content = "<h1>File Not Found</h1>";
                String error404 = "HTTP/1.1 404 File Not Found\r\nContent-Type:text/html\r\nContent-Length:" + content.length()
                        + "\r\n\r\n" + content;
                outputStream.write(error404.getBytes());
            }
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getCharacterEncoding() {
        return null;
    }

    @Override
    public String getContentType() {
        return null;
    }

    @Override
    public ServletOutputStream getOutputStream() throws IOException {
        return null;
    }

    @Override
    public PrintWriter getWriter() throws IOException {
        if (printWriter == null) {
            printWriter = new PrintWriter(outputStream, true);
        }
        return printWriter;
    }

    @Override
    public void setCharacterEncoding(String s) {

    }

    @Override
    public void setContentLength(int i) {

    }

    @Override
    public void setContentType(String s) {

    }

    @Override
    public void setBufferSize(int i) {

    }

    @Override
    public int getBufferSize() {
        return 0;
    }

    @Override
    public void flushBuffer() throws IOException {

    }

    @Override
    public void resetBuffer() {

    }

    @Override
    public boolean isCommitted() {
        return false;
    }

    @Override
    public void reset() {

    }

    @Override
    public void setLocale(Locale locale) {

    }

    @Override
    public Locale getLocale() {
        return null;
    }
}
